package com.estate.controller;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.estate.pojo.User;

@Controller
public class loginController {

	private Logger logger = Logger.getLogger(loginController.class);

	// 登录路径
	@RequestMapping("/login")
	private ModelAndView login(ModelAndView model) {
		model.setViewName("thymeleaf/login");
		return model;
	}

	// 登陆提交地址，和applicationContext-shiro.xml中配置的loginurl一致
	@RequestMapping(value="/dologin" ,method=RequestMethod.POST)
	public ModelAndView dologin(ModelMap map, @RequestParam("username") String username,
			@RequestParam("password") String password,ModelAndView model,HttpSession session) throws Exception {
		String message = "";
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			// 把用户名密码封装为UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username.trim(), password.trim());
			// RememberMe 记住我属性
			token.setRememberMe(true);
			try {
				// 执行登录
				currentUser.login(token);
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				message = "账号不存在";
				model.addObject("message", message);
				model.setViewName("thymeleaf/login");
				return model;
			} catch (IncorrectCredentialsException e) {
				e.printStackTrace();
				message = "密码错误";
				model.addObject("message", message);
				model.setViewName("thymeleaf/login");
				return model;
			}
			// 所有认证时异常的父类.
			catch (AuthenticationException ae) {
				ae.printStackTrace();
				message = "未知错误";
				model.addObject("message", message);
				model.setViewName("thymeleaf/login");
				return model;
			}
		}

		// 从shiro的session中取User
		// 取身份信息
		User user = (User) currentUser.getPrincipal();
		// 通过map传到页面
		model.addObject("user", user);
		model.setViewName("common/header");
		session.setAttribute("user", user);
		logger.info("-------------进入主页面-------------");
		model.setViewName("thymeleaf/index");
		return model;
	}

	// 退出系统地址
	@RequestMapping("/logout.action")
	public String dologout() {
		return "thymeleaf/login";
	}

	// 欢迎页面路径
	@RequestMapping("/welcome")
	public String welcome() {
		return "thymeleaf/index";
	}
}
